package cn.jiyun.common;

import cn.jiyun.pojo.GeoResult;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class GeocodingService {

    @Value("${amap.key}")
    private String amapKey;

    public GeoResult getGeocode(String address) {
        RestTemplate restTemplate = new RestTemplate();
        String url = "https://restapi.amap.com/v3/geocode/geo?address="+address+"&output=JSON&key="+amapKey;
        ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
//        System.out.println(response);
        if (response.getStatusCode().is2xxSuccessful()) {
            String responseBody = response.getBody();
//            System.out.println(responseBody);
            try {
                ObjectMapper objectMapper = new ObjectMapper();
//                System.out.println(objectMapper);
                JsonNode rootNode = objectMapper.readTree(responseBody);
                System.out.println(rootNode);
                JsonNode geocodesNode = rootNode.path("geocodes").get(0);
//                System.out.println(geocodesNode);
                if (geocodesNode != null) {
                    String location = geocodesNode.path("location").asText();
//                    System.out.println(location);
                    return new GeoResult(location);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
